//
//  OTAProgressManager.swift
//  WearDu
//
//  Created by wang tiao on 2025/10/10.
//

import Foundation

/// OTA 升级的各个阶段
enum OTAStage: CaseIterable, Hashable {
    case ispOtaFileDownload
    case ispOtaFileUpload
    case ble
}

/// OTAProgressManager 的代理协议
protocol OTAProgressManagerDelegate: AnyObject {
    /// 每次进度更新都会触发
    func otaProgressManager(_ manager: OTAProgressManager, didUpdateOverallProgress progress: Double)
    
    /// 当某个阶段进度变化时触发
    func otaProgressManager(_ manager: OTAProgressManager, didUpdateStage stage: OTAStage, progress: Double)
    
    /// 当阶段完成时（进度=1）触发
    func otaProgressManager(_ manager: OTAProgressManager, didFinishStage stage: OTAStage)
}

/// OTA 进度管理器
final class OTAProgressManager {
    
    weak var delegate: OTAProgressManagerDelegate?
    
    /// 实际启用的阶段
    private let enabledStages: [OTAStage]
    
    /// 每个阶段的当前进度 (0~1)
    private var stageProgress: [OTAStage: Double] = [:]
    
    /// 每个阶段的权重 (自动归一化)
    private var stageWeights: [OTAStage: Double] = [:]
    
    /// 初始化
    init(enabledStages: [OTAStage], weights: [OTAStage: Double]? = nil) {
        self.enabledStages = enabledStages
        OTAStage.allCases.forEach { stageProgress[$0] = 0 }
        
        // 如果传了自定义权重就归一化，否则平均分配
        if let customWeights = weights {
            let total = customWeights.values.reduce(0, +)
            self.stageWeights = customWeights.mapValues { $0 / total }
        } else {
            let equalWeight = 1.0 / Double(enabledStages.count)
            enabledStages.forEach { stageWeights[$0] = equalWeight }
        }
    }
    
    /// 更新某个阶段进度
    func update(stage: OTAStage, progress: Double) {
        guard enabledStages.contains(stage) else { return }
        let clamped = min(max(progress, 0), 1)
        stageProgress[stage] = clamped
        
        delegate?.otaProgressManager(self, didUpdateStage: stage, progress: clamped)
        
        if clamped >= 1.0 {
            delegate?.otaProgressManager(self, didFinishStage: stage)
        }
        
        delegate?.otaProgressManager(self, didUpdateOverallProgress: overallProgress)
    }
    
    /// 总体进度 (0~1)
    var overallProgress: Double {
        guard !enabledStages.isEmpty else { return 0 }
        return enabledStages.reduce(0.0) { sum, stage in
            sum + (stageProgress[stage] ?? 0) * (stageWeights[stage] ?? 0)
        }
    }
}
